import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../model/register_model.dart';

class TokenService extends GetxService {
  static TokenService get to => Get.find();

  // Token相关常量
  static const String _tokenKey = 'access_token';
  // static const String _tokenTypeKey = 'token_type';
  // static const String _userInfoKey = 'user_info';

  // Token状态
  final RxString accessToken = ''.obs;
  final RxString tokenType = ''.obs;

  @override
  void onInit() {
    super.onInit();
    _loadTokenFromStorage();
  }

  /// 从本地存储加载Token
  Future<void> _loadTokenFromStorage() async {
    try {
      final prefs = await SharedPreferences.getInstance();

      final token = prefs.getString(_tokenKey) ?? '';
      // final type = prefs.getString(_tokenTypeKey) ?? '';

      accessToken.value = token;
      // tokenType.value = type;
    } catch (e) {
      print('加载Token失败: $e');
    }
  }

  /// 保存Token到本地存储
  Future<void> saveToken(RegisterModel registerModel) async {
    try {
      final prefs = await SharedPreferences.getInstance();

      await prefs.setString(_tokenKey, registerModel.access_token);

      // 更新内存中的值
      accessToken.value = registerModel.access_token;
    } catch (e) {}
  }

  /// 清除Token
  Future<void> clearToken() async {
    try {
      final prefs = await SharedPreferences.getInstance();

      await prefs.remove(_tokenKey);

      // 清空内存中的值
      accessToken.value = '';
      // tokenType.value = '';
    } catch (e) {}
  }

  /// 检查Token是否需要刷新
  bool get needsRefresh {
    return accessToken.value.isEmpty;
  }

  /// 获取完整的Authorization头
  String get authorizationHeader {
    if (accessToken.value.isEmpty) return '';
    return 'Bearer ${accessToken.value}';
  }

  /// 强制刷新Token（清除当前Token，触发重新注册）
  Future<void> forceRefresh() async {
    await clearToken();
    print('Token已强制刷新，需要重新注册');
  }
}
